<template>
  <div class="shopbag">
    <van-nav-bar
      title="购物袋"
      left-text="返回"
      left-arrow
      :fixed="true"
      @click-left="back"
      @click-right="editProduct"
    >
      <template #right v-if="shopbagData.length > 0">
        <div>{{ isEdit ? "完成" : "编辑" }}</div>
      </template>
    </van-nav-bar>
    <div class="shopbag-top"></div>
    <div v-if="shopbagData.length > 0">
      <van-swipe-cell
        :disabled="!isEdit"
        v-for="(item, index) in shopbagData"
        :key="index"
      >
        <van-cell :border="false">
          <div class="clearfix cell-box">
            <div class="fl check">
              <van-checkbox
                v-model="item.isCheck"
                icon-size="24px"
                checked-color="#0C34BA"
                @change="simpleSelect"
              ></van-checkbox>
            </div>
            <div class="fl pro-img">
              <img class="auto-img" :src="item.small_img" alt="" />
            </div>
            <div class="fl pro-info">
              <div class="text-box">
                <div class="clearfix">
                  <div class="fl text-name">{{ item.name }}</div>
                  <div class="fl text-rule">{{ item.rule }}</div>
                </div>
                <div class="text-enname">{{ item.enname }}</div>
              </div>
              <div class="price-box">
                <div class="fl price">￥{{ item.price }}</div>
                <div class="fr">
                  <van-stepper
                    v-model="item.count"
                    theme="round"
                    button-size="24"
                    disable-input
                    @change="modifyCount(item)"
                  />
                </div>
              </div>
            </div>
          </div>
        </van-cell>

        <template #right>
          <van-button
            square
            text="删除"
            color="#3D75FE"
            @click="removeOneShopbag(item.sid)"
          />
        </template>
      </van-swipe-cell>

      <div>
        <van-submit-bar
          v-show="!isEdit"
          :price="total"
          button-text="提交订单"
          button-color="#0C34BA"
          @submit="commit"
        >
          <van-checkbox
            v-model="allCheck"
            icon-size="24px"
            checked-color="#0C34BA"
            @click="allSelect"
            >全选</van-checkbox
          >
        </van-submit-bar>

        <van-submit-bar
          v-show="isEdit"
          button-text="删除选择"
          button-color="#0C34BA"
          @submit="removeMoreShopbag"
        >
          <van-checkbox
            v-model="allCheck"
            icon-size="24px"
            checked-color="#0C34BA"
            @click="allSelect"
            >全选</van-checkbox
          >
        </van-submit-bar>
      </div>
    </div>
    <div v-else>
      <van-empty description="空空如也,去逛逛?">
        <van-button round size="small" color="#0C34BA" @click="goMenu">逛一逛</van-button>
      </van-empty>
    </div>

    <!-- 猜你喜欢 -->
    <div class="hot-product">
      <div class="hot-product-title">猜你喜欢</div>
      <div class="product-box clearfix">
        <div
          class="product-item fl"
          :class="[index % 2 == 0 ? 'p-left' : 'p-right']"
          v-for="(item, index) in hotProducts"
          :key="index"
        >
          <div class="p-img" @click="viewProductInfo(item.pid)">
            <img class="auto-img" :src="item.smallImg" alt="" />
          </div>
          <div class="pro-name one-text">{{ item.name }}</div>
          <div class="clearfix">
            <!-- <div class="en-pro-name one-text fl">heitangbobo</div> -->
            <div class="pro-price fl">￥{{ item.price }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import "../../assets/less/shopbag.less";
import { utils } from "../../assets/js/utils";
export default {
  data() {
    return {
      isEdit: false,
      allCheck: false,
      total: 0,
      shopbagData: [],

      //热门推荐
      hotProducts: [],
    };
  },
  created() {
    console.log("shopbag");
    //查询购物袋数据
    this.findShopbag();

    //热门推荐商品数据
    this.getHotProducts();
  },

  methods: {
    //返回上次的页面
    back() {
      this.$router.go(-1);
    },

    //返回菜单
    goMenu() {
      this.$router.push({ name: "Menu" });
    },

    //提交订单
    commit() {
      //查找需要购买的商品,  sid
      let sids = [];
      this.shopbagData.map((v) => {
        if (v.isCheck) {
          sids.push(v.sid);
        }
      });

      sids = sids.join("-");

      this.$router.push({ name: "Pay", query: { sids } });
    },

    //编辑商品
    editProduct() {
      this.isEdit = !this.isEdit;
    },

    //查询购物袋数据
    findShopbag() {
      //获取token字符串
      let tokenString = localStorage.getItem("CSTK");
      if (!tokenString) {
        return;
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
        loadingType: "spinner",
      });

      this.axios({
        method: "GET",
        url: "/findAllShopcart",
        params: {
          appkey: this.appkey,
          tokenString,
        },
      })
        .then((result) => {
          this.$toast.clear();
          console.log("find shopcartbag result ==>", result);
          if (result.data.code == 5000) {
            result.data.result.map((v) => {
              v.isCheck = false;
            });
            this.shopbagData = result.data.result;
          } else {
            this.$toast(result.data.msg);
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==>", err);
        });
    },

    //全选
    allSelect() {
      this.shopbagData.map((v) => {
        v.isCheck = this.allCheck;
      });

      this.sum();
    },

    //单选
    simpleSelect() {
      this.sum();

      for (let i = 0; i < this.shopbagData.length; i++) {
        if (!this.shopbagData[i].isCheck) {
          this.allCheck = false;
          return;
        }
      }
      this.allCheck = true;
    },

    //修改商品数量
    modifyCount(item) {
      //获取token字符串
      let tokenString = localStorage.getItem("CSTK");
      if (!tokenString) {
        return;
      }

      //参数序列化
      let data = utils.queryString({
        appkey: this.appkey,
        tokenString,
        sid: item.sid,
        count: item.count,
      });

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
        loadingType: "spinner",
      });

      this.axios({
        method: "POST",
        url: "/modifyShopcartCount",
        data,
      })
        .then((result) => {
          this.$toast.clear();
          console.log("result ==>", result);

          this.sum();

          if (result.data.code !== 6000) {
            this.$toast(result.data.msg);
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==>", err);
        });
    },

    //删除购物袋数据
    removeShopbag(sids) {
      // sids:  sid的集合,类型: array

      //获取token字符串
      let tokenString = localStorage.getItem("CSTK");
      if (!tokenString) {
        return;
      }

      //参数序列化
      let data = utils.queryString({
        appkey: this.appkey,
        tokenString,
        sids: JSON.stringify(sids),
      });

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
        loadingType: "spinner",
      });

      return this.axios({
        method: "POST",
        url: "/deleteShopcart",
        data,
      });
    },

    //删除单个购物袋
    removeOneShopbag(sid, index) {
      this.removeShopbag([sid])
        .then((result) => {
          this.$toast.clear();
          console.log("result ==>", result);
          if (result.data.code == 7000) {
            this.shopbagData.splice(index, 1);
          }
          this.$toast(result.data.msg);

          this.sum();
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==>", err);
        });
    },

    //删除多个购物袋
    removeMoreShopbag() {
      //查找选择购物袋
      let sids = [];
      this.shopbagData.map((v) => {
        if (v.isCheck) {
          sids.push(v.sid);
        }
      });

      this.removeShopbag(sids)
        .then((result) => {
          this.$toast.clear();
          console.log("result ==>", result);
          if (result.data.code == 7000) {
            for (let i = this.shopbagData.length - 1; i >= 0; i--) {
              if (this.shopbagData[i].isCheck) {
                this.shopbagData.splice(i, 1);
              }
            }
            this.sum();
          }
          this.$toast(result.data.msg);
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==>", err);
        });
    },

    //计算总金额
    sum() {
      this.total = 0;
      this.shopbagData.map((v) => {
        if (v.isCheck) {
          this.total += v.count * v.price;
        }
      });
      this.total *= 100;
    },

    //猜你喜欢
    //获取推荐商品数据
    getHotProducts() {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
        loadingType: "spinner",
      });
      this.axios({
        method: "GET",
        url: "/typeProducts",
        //如果get请求，参数需要放在params, 如果是post请求,参数需要放在data
        params: {
          appkey: this.appkey,
          key: "isHot",
          value: 1,
        },
      })
        .then((result) => {
          this.$toast.clear();
          console.log("result ==> ", result);
          if (result.data.code == 500) {
            this.hotProducts = result.data.result;
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },

    //查看商品详情
    viewProductInfo(pid) {
      this.$router.push({ name: "Detail", query: { pid } });
    },
  },
};
</script>
